<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left back-icon" @click="goBack"></i>
      <p>用户注册</p>
    </header>

    <!-- 表单部分 -->
    <ul class="form-box">
      <!-- 手机号码输入 -->
      <li class="sty1">
        <div class="title">手机号码：</div>
        <div class="content">
          <!-- 删除oninput中的复杂校验 -->
          <input type="text" v-model="user.userId" placeholder="手机号码" id="mobileNo">
        </div>
      </li>


      <!-- 密码输入 -->
      <li class="sty1">
        <div class="title">
          密码：
        </div>
        <div class="content">
          <input type="password" v-model="user.password" placeholder="请输入密码">
        </div>
      </li>

      <!-- 确认密码输入 -->
      <li class="sty1">
        <div class="title">
          确认密码：
        </div>
        <div class="content">
          <input type="password" v-model="confirmPassword" placeholder="确认密码">
        </div>
      </li>

      <!-- 用户名称输入 -->
      <li class="sty1">
        <div class="title">
          用户名称：
        </div>
        <div class="content">
          <input type="text" v-model="user.userName" placeholder="用户名称">
        </div>
      </li>

      <!-- 性别选择 -->
      <li class="sty1">
        <div class="title">
          性别：
        </div>
        <div class="content" style="font-size: 3vw;">
          <input type="radio" v-model="user.userSex" value="1" style="width:6vw;height: 3.2vw;">男
          <input type="radio" v-model="user.userSex" value="0" style="width:6vw;height: 3.2vw;">女
        </div>
      </li>

      <!-- 身份选择 -->
      <li class="sty1">
        <div class="title">
          身份选择：
        </div>
        <div class="content" style="font-size: 3vw;">
          <input type="radio" v-model="user.usertype" value="customer" style="width:6vw;height: 3.2vw;">顾客
          <input type="radio" v-model="user.usertype" value="merchant" style="width:6vw;height: 3.2vw;">商家
        </div>
      </li>

      <!-- 头像选择 -->
      <li class="sty2">
        <div class="title">
          用户头像：
        </div>
        <ul class="imgtype">
          <li @click="selectImg(1)" :class="{ selected: selectedAvatar === 1 }">
            <img src="/assets/t1.png">
          </li>
          <li @click="selectImg(2)" :class="{ selected: selectedAvatar === 2 }">
            <img src="/assets/t2.png">
          </li>
          <li @click="selectImg(3)" :class="{ selected: selectedAvatar === 3 }">
            <img src="/assets/t3.png">
          </li>
          <li @click="selectImg(4)" :class="{ selected: selectedAvatar === 4 }">
            <img src="/assets/t4.png">
          </li>
          <li @click="selectImg(5)" :class="{ selected: selectedAvatar === 5 }">
            <img src="/assets/t5.png">
          </li>
          <li @click="selectImg(6)" :class="{ selected: selectedAvatar === 6 }">
            <img src="/assets/t6.png">
          </li>
          <li @click="selectImg(7)" :class="{ selected: selectedAvatar === 7 }">
            <img src="/assets/t7.png">
          </li>
          <li @click="selectImg(8)" :class="{ selected: selectedAvatar === 8 }">
            <img src="/assets/t8.png">
          </li>
          <li @click="selectImg(9)" :class="{ selected: selectedAvatar === 9 }">
            <img src="/assets/t9.png">
          </li>
        </ul>
      </li>
    </ul>

    <!-- 注册按钮部分 -->
    <div class="button-login">
      <button @click="register">注册</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterPage',
  data() {
    return {
      user: {
        userId: '',
        password: '',
        userName: '',
        userSex: 1,
        userImg: '', // 保存选中的头像
        usertype: 'customer' // 默认选择顾客身份
      },
      confirmPassword: '',
      selectedAvatar: null // 保存选中的头像索引
    }
  },

  methods: {
    selectImg(index) {
      const imgPath = `/assets/t${index}.png`;
      const img = new Image();
      img.src = imgPath;
      img.crossOrigin = 'Anonymous';

      img.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);

        const dataURL = canvas.toDataURL('image/png');
        this.user.userImg = dataURL;
      };

      this.selectedAvatar = index;
    },
    checkUserId() {
      if (!this.user.userId) {
        alert('手机号码不能为空！');
      } else {
        // 不再进行复杂的正则校验
        // 提交给后端进行唯一性检查
        this.$axios.post('UserController/getUserById', this.$qs.stringify({
          userId: this.user.userId,
        })).then(response => {
          if (response.data == 1) {
            this.user.userId = '';
            alert('此手机号码已存在！');
          }
        }).catch(error => {
          console.error(error);
        });
      }
    },
    register() {
      console.log(this.user);  // 确认此处输出包含 usertype

      if (this.user.password.length < 1) {
        alert('密码长度应不少于1位！');
        return;
      }
      if (this.user.password != this.confirmPassword) {
        alert('两次输入的密码不一致！');
        return;
      }
      if (this.user.userName == '') {
        alert('用户名不能为空！');
        return;
      }
      if (!this.user.userImg) {
        alert('请选择一个头像！');
        return;
      }

      // 提交用户注册信息，包括身份类型（顾客/商家）
      this.$axios.post('UserController/saveUser', this.user)
        .then(response => {
          if (response.data.success) {
            const userId = response.data.userId;

            if (this.user.usertype === 'merchant') {
              this.business = {
                businessId: userId,
                businessName: this.user.userName,
                businessImg: this.user.userImg,
              };
              this.saveBusiness(this.business);
            } else {
              alert('注册成功！');
              this.$router.push('/login');
            }
          } else {
            alert(`注册失败：${response.data.message || response.data.error}`);
          }
        })
        .catch(error => {
          console.error(error);
        });
    },



    // 保存商家信息的函数
    saveBusiness(business) {
      this.$axios.post('BusinessController/saveBusiness', business)
        .then(response => {
          if (response.data.success) {
            alert('商家信息保存成功！');
            this.$router.push('/login'); // 跳转到登录页面
          } else {
            alert('商家信息保存失败，请稍后重试！');
          }
        })
        .catch(error => {
          console.error('商家信息保存失败', error);
          alert('商家信息保存失败，请稍后重试！');
        });
    }


  }
}
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background: royalblue;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 表单部分 ******************/
.wrapper .form-box {
  width: 100%;
  margin-top: 12vw;
}

.wrapper .form-box .sty1 {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  align-items: center;
}

.wrapper .form-box .sty2 {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  flex-direction: column;
}

.wrapper .form-box .sty1 .title {
  flex: 0 0 18vw;
  font-size: 3vw;
  font-weight: 700;
  color: #666;
}

.wrapper .form-box .sty2 .title {
  flex: 0 0 10vw;
  font-size: 3vw;
  font-weight: 700;
  color: #666;
}

.wrapper .form-box .sty2 .imgtype {
  width: 90%;
  display: flex;
  /*自动换行*/
  flex-wrap: wrap;
  justify-content: space-around;
  /*把两行当成整体居中 align-items各自居中*/
  align-content: center;
  margin-left: 18px;
}

.wrapper .form-box .sty2 .imgtype li {
  /*实现一排3个*/
  width: 33.33%;
  height: 33.33%;

  display: flex;
  /*改变主轴方向*/
  flex-direction: column;
  justify-content: center;
  align-items: center;

  user-select: none;
  /*鼠标悬浮变成手的样式*/
  cursor: pointer;
}

.wrapper .form-box .sty2 .imgtype li img {
  width: 70%;
  height: auto;
  border-radius: 50%;
  padding-bottom: 20px;
}

.wrapper .form-box .sty1 .content {
  flex: 1;
}

.wrapper .form-box .sty1 .content input {
  border: none;
  outline: none;
  width: 100%;
  height: 4vw;
  font-size: 3vw;
}

.wrapper .button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.wrapper .button-login button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background: blue;
  border-radius: 4px;
  border: none;
  outline: none;
}

.wrapper .button-register {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.wrapper .button-register button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #666;
  background-color: #EEE;
  border-radius: 4px;
  border: none;
  outline: none;
  border: solid 1px #DDD;
}

.selected img {
  border: 2px solid royalblue;
  /* 为选中的头像添加蓝色边框 */
  border-radius: 50%;
  /* 保持圆形 */

}

/* 返回箭头的样式 */
.back-icon {
  font-size: 36px;
  /* 设置图标的大小 */
  position: fixed;
  /* 固定在页面上，不会随内容滚动 */
  top: 13px;
  /* 距离页面顶部 13px */
  left: 20px;
  /* 距离页面左侧 20px */
  color: #1a2edf;
  /* 设置图标的颜色 */
  cursor: pointer;
  /* 鼠标悬停时显示为手型 */
}
</style>